/*
 * PsParser.h
 *
 *  Created on: 2017年4月18日
 *      Author: chuanjiang.zh
 */

#ifndef PSPARSER_H_
#define PSPARSER_H_

#include "BasicType.h"
#include "TIOBuffer.h"
#include "MediaFormat.h"
#include "DoubleByteBuffer.h"


namespace av
{

class PsParser
{
public:
	struct Packet
	{
    	uint8_t     type;
        uint8_t*    data;
        size_t      length;
        int64_t		ts;
        int 		flags;

		Packet():
			type(),
			data(),
			length(),
			ts(),
			flags()
		{
		}
	};

public:
	PsParser();
	virtual ~PsParser();

    /**
     * 输入字节流, 获取媒体包
     * @param data	字节数组指针
     * @param length	字节数组长度
     * @param pkt
     * @return true 表示有解析出媒体包
     */
    bool parse(const uint8_t* data, size_t length, Packet& pkt);

    /**
     * 重置清理
     */
    void clear();

    const MediaFormat& getFormat();

protected:
	size_t parsePacket(uint8_t* data, size_t length, bool& found, Packet& packet);

	size_t parsePackHeader(uint8_t* data, size_t length);
	size_t parseSystemHeader(uint8_t* data, size_t length);
	size_t parsePsmHeader(uint8_t* data, size_t length);
	size_t parseJump(uint8_t* data, size_t length);
	size_t parsePesPacket(int streamType, uint8_t* data, size_t length, bool& found, Packet& packet);

    bool parsePacket(Packet& packet);

    bool parsePESPacket(Packet& packet);

    bool parsePackHeader(Packet& packet);
    bool parseSystemHeader(Packet& packet);
    bool parsePsmHeader(Packet& packet);

    void parseStreamInfo(uint8_t stream_id, uint8_t stream_type, uint8_t* data, int length);

    bool startWithCode(const uint8_t* buffer, size_t length);
    size_t findStartCode(const uint8_t* buffer, size_t length);
    size_t findStartCode(const uint8_t* buffer, size_t offset, size_t length);
    size_t findHeaderStartCode(const uint8_t* buffer, size_t offset, size_t length);

    bool flushPacket();

	void logData(const char* name, const uint8_t* data, int size);

private:
    MediaFormat		m_format;
    comn::IOBuffer  m_buffer;

    DoubleByteBuffer	m_pktBuffer;
    Packet	m_pkt;

    Packet	m_outPkt;

    bool	m_imkh;
	int		m_lostCount;

};



} /* namespace av */

#endif /* PSPARSER_H_ */
